package com.smedi.ismedi.web.starter.util;

import cn.hutool.core.util.IdUtil;
import com.smedi.ismedi.authority.starter.exception.BasicError;
import com.smedi.ismedi.authority.starter.exception.LogicException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @Author: xulinjun
 * @Date: 2021-6-17 11:37
 */
@Slf4j
@Component
public class BaseUtil {
    /**
     * base64代码转临时文件
     *
     * @param base64
     * @param suffix
     * @return
     */
    public File base64ToTempFile(String base64, String suffix) {
        String data = base64.toString().replace("\r\n", "");
        try {
            // 临时文件
            File file = File.createTempFile(IdUtil.simpleUUID(), suffix);
            BufferedOutputStream bos = null;
            FileOutputStream fos = null;
            try {
                BASE64Decoder decoder = new BASE64Decoder();
                byte[] bytes = decoder.decodeBuffer(data);
                fos = new FileOutputStream(file);
                bos = new BufferedOutputStream(fos);
                bos.write(bytes);
            } finally {
                if (bos != null) {
                    try {
                        bos.close();
                    } catch (IOException e) {
                        throw LogicException.raise(BasicError.UN_HANDLER_EXCEPTION, e);
                    }
                }
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        throw LogicException.raise(BasicError.UN_HANDLER_EXCEPTION, e);
                    }
                }
            }
            return file;
        } catch (Exception e) {
            throw LogicException.raise(BasicError.UN_HANDLER_EXCEPTION, e);
        }
    }
}
